<template>
    <div class="branding" v-loading="loading">

        <UserFixedHead :title="detail.id ? 'Edit hang tag' : 'Create hang tag'" />

        <h2 v-text="detail.id ? 'Edit hang tag' : 'Create hang tag'"></h2>

        <div class="branding-warp">
            <div class="branding-nav">
                <span @click="$emit('close')">Hang tag</span>
                <i class="iconfont icon-you"></i>
                <strong v-text="detail.id ? 'Edit hang tag' : 'Create hang tag'"></strong>
            </div>

            <div class="branding-name" :currency="currency">
                <label>
                    <strong>Hang tag name</strong>
                    <input type="text" v-model="form.template_name" @input="checkChange()" maxlength="64" placeholder="Tag name" />
                </label>
                <p>
                    <strong>Print cost</strong>
                    <em v-if="designList.length == 0">-</em>
                    <em v-else-if="!form.extra_price">Free</em>
                    <CommonCurrencyRate v-else :price="form.extra_price" type="unit|price" />
                </p>
                <p>
                    <strong>Material cost</strong>
                    <em v-if="!form.hang_tag_id">-</em>
                    <CommonCurrencyRate v-else :price="form.shape_price" type="unit|price" />
                </p>
                <p>
                    <strong>Unit price</strong>
                    <em v-if="!form.shape_price && !form.extra_price">-</em>
                    <CommonLevelDiscount v-else :price="form.shape_price + form.extra_price" :level="userInfo.level" type="unit|original|discount|icon" />
                </p>

            </div>

            <!-- 预览 -->
            <div class="branding-preview">
                <div class="branding-preview-design">
                    <h3>Design</h3>
                    <p v-if="designList.length == 0">
                        <img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-nodesign.png" alt="">
                        <span>Your design can be used on any type of hang tag.</span>
                    </p>

                    <ul v-else>
                        <li v-for="piece in designList" :key="piece.canvas_name">
                            <figure>
                                <b :style="{paddingBottom:100 * piece.canvas_height / piece.canvas_width + '%'}"></b>
                                <CommonDesignSurfacePreivew :pieces="form.design" :surface="getPieceSurface(piece)" type="piece" />
                            </figure>
                            <span v-text="piece.canvas_name"></span>
                        </li>
                    </ul>

                    <button type="primary" @click="setEditor()" v-text="designList.length > 0 ? 'Edit' : 'Add design'"></button>
                </div>

                <div class="branding-preview-type">
                    <h3>Hang tag type</h3>
                    <p v-if="!form.hang_tag_id">
                        <img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-noshape.png" alt="">
                        <span>Pick your favorite type of hang tag(more coming).</span>
                    </p>
                    <div class="branding-preview-model" v-else>
                        <ul>
                            <li v-for="surface in form.model_img" :key="surface.canvas_name">
                                <CommonDesignSurfacePreivew :pieces="form.design" :surface="surface" />
                                <span v-text="surface.canvas_name"></span>
                            </li>
                        </ul>
                        <p>
                            <strong v-text="form.name"></strong>
                            <span v-text="form.description"></span>
                        </p>
                    </div>
                    <button type="primary" @click="setShape()">Choose now</button>
                </div>
            </div>

            <div class="branding-save" :class="{ active: change }">
                <cite>
                    <button @click="$emit('close')">Cancel</button>
                    <button type="primary" @click="updateBrand()">Save</button>
                </cite>
            </div>
        </div>

        <!-- 编辑器 -->
        <UxDialog :visible="!!editor" class="design-editor-dialog" title="Custom hang tag" :can-close="false">
            <CommonDesignEditor v-if="editor" :design="editor.design" @close="editor.close($event)" @update="editor.save($event)" />
        </UxDialog>

        <!-- 选择款式 -->
        <UxDialog :visible="!!shape" @close="shape && shape.close($event)" title="Hang tags">
            <BrandingHangtagShape v-if="shape" :shape="shape" @select="shape.save($event)" />
        </UxDialog>

        <!-- 保存 -->
        <UxDialog :visible="!!saving" class="saving-dialog" :status="saving" :can-close="false">

            <div class="saving-loading" v-if="saving=='loading'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-saving.png" alt="" />
                </figure>
                <img src="@/assets/images/pay-loading.gif" />
                <strong>Your design is being saved</strong>
            </div>

            <div class="saving-success" v-if="saving=='success'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-saving-success.png" alt="" />
                </figure>
                <p><span>Successfully saved</span></p>
                <fieldset>
                    <button type="primary" @click="onSuccess()">OK</button>
                </fieldset>
            </div>

            <div class="saving-failure" v-if="saving=='failure'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-saving-failure.png" alt="" />
                </figure>
                <p>
                    <strong>Failed to save</strong><span>Please check your network</span>
                </p>
                <fieldset>
                    <button v-if="editor" @click="editor.save(editor.pieces)">Save again</button>
                    <button v-else @click="updateBrand()">Save again</button>
                </fieldset>
            </div>
        </UxDialog>

    </div>
</template>
<script>
import DesignResource from "@/utils/DesignResource.js";
import { mapGetters, mapState } from "vuex";
export default {
    name: "HangtagManage",
    props: {
        detail: { type: Object, default: false },
    },
    data () {
        return {
            editor: null,
            change: false,
            shape: null,
            saving: '',
            loading: false,
            cache: '',
            form: {
                template_name: '',
                name: '',
                description: '',
                design: [],
                model_img: [],
                hang_tag_id: 0,
                extra_price: 0,
                shape_price: 0,
            },
        };
    },
    computed: {
        ...mapState({
            currency: 'currency',
            rate: 'rate',
        }),
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        designList () {
            return this.form.design.filter(i => i.layers.length > 0);
        }
    },
    methods: {
        // 保存或更新
        async updateBrand () {
            if (!this.detail) {
                // 没有详情不保存
            } else if (!this.form.template_name) {
                this.$uxMessage.error("Please name your hang tag.");
            } else {

                // 先生成图片，再保存数据
                const design = this.form.design;
                const print = design.filter(piece => piece.layers.length > 0).map(i => { return { ...i, width_product: true } })
                const drawer = {
                    spu: 'hangtag',
                    pieces: print,
                    models: [],
                }

                this.saving = 'loading';
                this.$http("Drawer.batchDraw", drawer).then((response) => {
                    if (response.code === 0) {
                        // 保存成功，修改output
                        const drawObject = Object.fromEntries(response.data.map((i) => [i.name, i]));
                        const httpKey = this.detail.id ? "BrandHangtag.update/" + this.detail.id : "BrandHangtag.insert";
                        const request = {
                            template_name: this.form.template_name,
                            model_img: this.form.model_img,
                            hang_tag_id: this.form.hang_tag_id,
                            extra_price: this.form.extra_price,
                            design: '',
                        }

                        if (this.designList.length > 0) {
                            request.design = this.form.design.map(item => {
                                const draw = drawObject[item.canvas_name]
                                if (item.layers.length == 0) {
                                    // 空的设计
                                    item.output_img = ''
                                } else if (draw) {
                                    const output = draw.output || ''
                                    item.output_img = output.replace(/-litimg(\.(jpe?g|png))/gi, "$1");
                                }
                                return {
                                    ...item,
                                    layers: JSON.stringify(item.layers)
                                }
                            })
                        } else {
                            request.design = ''
                        }

                        return this.$http(httpKey, request);
                    } else {
                        return Promise.reject(response);
                    }

                }).then(response => {
                    if (response.code === 0) {
                        this.saving = 'success';
                        this.cache = JSON.stringify(this.form);
                        this.checkChange();
                    } else {
                        this.saving = 'failure';
                    }

                }).catch(error => {
                    this.saving = 'failure';
                })


            }
        },

        // 初始化数据
        getDetail () {

            const design = [
                { "id": 1, price: 99, "mask_image": "hangtag/front1669275939875.svg", "output_img": "", "outer_width": 2048, "outer_height": 2048, "surface_name": "Front Side", "canvas_name": "Front Side", "real_width": 420, "real_height": 750, "canvas_width": 816, "canvas_height": 1456, "canvas_left": 616, "canvas_top": 450, "canvas_rotate": 0, "layers": [] },
                { "id": 2, price: 99, "mask_image": "hangtag/front1669275939875.svg", "output_img": "", "outer_width": 2048, "outer_height": 2048, "surface_name": "Back Side", "canvas_name": "Back Side", "real_width": 420, "real_height": 750, "canvas_width": 816, "canvas_height": 1456, "canvas_left": 616, "canvas_top": 450, "canvas_rotate": 0, "layers": [] }
            ];


            if (this.detail.id) {

                this.form.template_name = this.detail.template_name;
                this.form.name = this.detail.name;
                this.form.description = this.detail.description;
                this.form.hang_tag_id = this.detail.hang_tag_id;
                this.form.extra_price = this.detail.extra_price || 0;
                this.form.shape_price = this.detail.price || 0;
                this.form.design = this.detail.design_list.length > 0 ? this.detail.design_list : design;
                this.form.model_img = this.detail.model_img || [];

                // 设计区要置顶
                this.form.model_img.map(item => {
                    item.mapping_top = true;
                })

            } else {

                this.form.template_name = '';
                this.form.name = '';
                this.form.description = '';
                this.form.hang_tag_id = 0;
                this.form.extra_price = 0;
                this.form.shape_price = 0;
                this.form.model_img = [];
                this.form.design = design;
            }


            // 缓存
            this.cache = JSON.stringify(this.form);

            // 预加载
            this.form.design.map(piece => {

                const option = { type: "simple", form: "materials" };
                // 加载背景图
                piece.mask_image && DesignResource.loadImage(piece.mask_image);

                // 加载设计图
                piece.layers.map(layer => {
                    layer.type == 'image' && layer.url && DesignResource.loadImage(layer.url, option)
                })
            });

            // 加载字体
            DesignResource.loadAllFont();
        },

        // 编辑窗口
        setEditor () {
            this.editor = {
                spu: 'hangtag',
                design: this.form.design,
                close: (change) => {
                    if (change) {
                        this.$parent.dialog_leave = (leave) => {
                            if (leave) {
                                this.editor = null
                                this.$parent.dialog_leave = null;
                            } else {
                                this.$parent.dialog_leave = null;
                            }
                        };
                    } else {
                        this.editor = null
                    }
                },
                save: (design) => {

                    // 要优惠一个面,价格最高的面
                    const prices = design.map(piece => piece.layers.length > 0 ? piece.price : 0)
                    const discount = Math.max(...prices)

                    this.form.extra_price = prices.reduce((p, c) => p + c, 0) - discount;
                    this.form.design = design.slice(0);
                    this.editor = null
                    this.checkChange();
                },
            }
        },

        // 选择款式
        setShape () {
            this.shape = {
                active: {
                    design_model: this.form.model_img,
                    id: this.form.hang_tag_id,
                    price: this.form.shape_price,
                    name: this.form.name,
                    description: this.form.description,
                },
                close: () => {
                    this.shape = null;
                },
                save: (hangtag) => {
                    this.form.model_img = hangtag.design_model;
                    this.form.hang_tag_id = hangtag.id;
                    this.form.shape_price = hangtag.price;
                    this.form.name = hangtag.name;
                    this.form.description = hangtag.description;
                    this.shape = null;
                    this.checkChange();
                },
            }
        },
        getPieceSurface (piece) {

            const maxSize = Math.max(piece.canvas_width, piece.canvas_height) || 1;
            const width = piece.outer_width * piece.canvas_width / maxSize;
            const height = piece.outer_height * piece.canvas_height / maxSize;
            const left = (piece.outer_width - width) / 2;
            const top = (piece.outer_height - height) / 2;

            return {
                "surface_name": piece.canvas_name,
                "name": piece.canvas_name,
                "mask_image": null,
                "outer_width": piece.outer_width,
                "outer_height": piece.outer_height,
                "mask_color": "",
                "mask_opacity": 0,
                "mapping_top": true,
                "mapping": [{
                    "canvas_name": piece.canvas_name,
                    "variant_deform": 0,
                    "variant_factor": 0,
                    "height": height,
                    "width": width,
                    "rotate": 0,
                    "clip": "",
                    "x": left,
                    "y": top
                }]
            }

        },

        // 判断是否有更新
        checkChange () {
            this.change = JSON.stringify(this.form) != this.cache;
        },
        // 保存成功
        onSuccess () {
            if (this.editor) {
                this.editor = null;
                this.saving = '';
            } else {
                this.saving = '';
                this.$nextTick(e => {
                    this.$emit("update");
                    this.$emit("close");
                })
            }
        }
    },
    created () {
        this.getDetail();
    },
};
</script>

<style lang="scss" scoped>
.design-editor-dialog {
    padding: 0 !important;
    background: none !important;

    &::v-deep > .dialog-content {
        border-radius: 0;

        & > h2 {
            height: 78px;
            line-height: 78px;
            font-size: 24px;
            font-weight: bold;
            color: #000000;
        }

        .dialog-body {
            display: flex;
            display: flex;
            width: 100vw;
            height: calc(100vh - 40px);

            .tooler-nodata figure {
                width: 140px;
                &::before {
                    background-image: url(https://img.podpartner.com/static/images-20230202/brand/hangtag-design-nodata.png);
                    background-size: 100% 100%;
                }
                svg {
                    display: none;
                }
            }
        }
    }
}
.branding {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;

    & > h2 {
        line-height: 72px;
        background: #fff;
        border-radius: 8px;
        font-size: 32px;
        color: #000000;
        text-align: center;
    }

    .branding-warp {
        flex: 1;
        background: #fff;
        border-radius: 8px;
        padding-bottom: 80px;
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;

        & > * {
            width: 100%;
            max-width: 832px;
        }
    }
}

.branding-nav {
    padding: 28px 0 24px;
    height: 16px;
    font-size: 14px;
    color: #555555;
    line-height: 16px;
    display: flex;

    span {
        cursor: pointer;

        &:hover {
            color: #ea4c89;
        }
    }

    i {
        display: inline-block;
        margin: 0 8px;
        width: 12px;
        height: 16px;
        font-size: 12px;
    }

    strong {
        font-weight: normal;
        color: #000;
    }
}

.branding-name {
    display: flex;
    padding: 28px 20px;
    background: #f6f6f6;
    border-radius: 5px;
    box-sizing: border-box;

    label {
        flex: 1;
    }

    strong {
        font-size: 16px;
        color: #000000;
        line-height: 18px;
        display: block;
        padding-bottom: 12px;
        white-space: nowrap;
    }

    p {
        margin-left: 48px;
        width: 108px;
        position: relative;
        strong {
            display: block;
            text-align: center;
            font-size: 14px;
        }
        em,
        .currency-rate {
            display: block;
            text-align: center;
            justify-content: center;
            align-items: center;
            border-radius: 8px;
            border: 1px solid #e3e3e3;
            height: 40px;
            line-height: 40px;
            font-size: 16px;
            color: #555555;
            box-sizing: border-box;
            position: relative;
        }

        .level-discount {
            display: flex;
            text-align: center;
            justify-content: center;
            align-items: center;
            border-radius: 8px;
            border: 1px solid #e3e3e3;
            height: 40px;
            line-height: 40px;
            font-size: 14px;
            box-sizing: border-box;
            position: relative;
        }

        &:last-child {
            width: 160px;
            em,
            .currency-rate,
            .level-discount {
                background: rgba($color: #000000, $alpha: 0.04);
                border-color: rgba($color: #000000, $alpha: 0.04);
            }
        }

        &:nth-child(2) em,
        &:nth-child(2) .currency-rate {
            &::before {
                content: '';
                position: absolute;
                left: 100%;
                top: 50%;
                margin-left: 18px;
                margin-top: -1px;
                width: 12px;
                height: 2px;
                background: #555555;
                border-radius: 1px;
            }
            &::after {
                content: '';
                position: absolute;
                left: 100%;
                top: 50%;
                margin-top: -6px;
                margin-left: 23px;
                width: 2px;
                height: 12px;
                background: #555555;
                border-radius: 1px;
            }
        }
        &:nth-child(3) em,
        &:nth-child(3) .currency-rate {
            &::before {
                content: '';
                position: absolute;
                top: 50%;
                left: 100%;
                margin-left: 18px;
                margin-top: -3px;
                width: 12px;
                height: 2px;
                background: #555555;
                border-radius: 1px;
            }
            &::after {
                content: '';
                position: absolute;
                top: 50%;
                left: 100%;
                margin-left: 18px;
                margin-top: 1px;
                width: 12px;
                height: 2px;
                background: #555555;
                border-radius: 1px;
            }
        }
    }

    &[currency='JPY'] {
        strong,
        em,
        .currency-rate {
            font-size: 14px;
        }
    }
}
.branding-preview {
    margin-top: 40px;
    display: flex;

    h3 {
        font-size: 16px;
        color: #000000;
        line-height: 18px;
        padding-bottom: 12px;
        width: 100%;
        text-align: left;
    }

    button {
        margin-top: 24px;
        width: 140px;
        height: 40px;
        font-size: 14px;
    }

    .branding-preview-design,
    .branding-preview-type {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .branding-preview-design {
        & > ul {
            width: 100%;
            height: 394px;
            background-color: #f0f0f0;
            border-radius: 8px;
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;

            li {
                display: flex;
                flex-direction: column;
                width: 152px;
                margin: 0 10px 0;
                box-sizing: border-box;
            }

            .surface-preview {
                position: absolute;
                height: 100%;
                width: 0;
                padding: 0;
                top: 0;
                left: 50%;
                display: flex;

                &::v-deep {
                    canvas {
                        width: auto !important;
                        left: 50%;
                        transform: translateX(-50%);
                    }
                }
            }

            figure {
                position: relative;
                padding: 0;
                border: 20px solid #fafafa;
                background-color: #fafafa;
                border-radius: 8px;
                overflow: hidden;
                & > b {
                    display: block;
                }
                &::before {
                    content: '';
                    position: absolute;
                    left: 0;
                    top: 0;
                    right: 0;
                    bottom: 0;
                    border: 1px dashed #bdbdbd;
                }
            }
            span {
                text-align: center;
                margin-top: 12px;
                font-size: 14px;
                font-weight: bold;
                color: #000000;
                line-height: 16px;
            }
        }

        & > p {
            height: 394px;
            width: 100%;
            position: relative;
            background-color: #f0f0f0;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            align-items: center;

            & > img {
                margin-top: 105px;
                width: 108px;
                height: 109px;
            }
            & > span {
                margin: 38px 60px;
                font-size: 16px;
                font-weight: bold;
                color: #555555;
                line-height: 20px;
                text-align: center;
            }
        }
    }

    .branding-preview-model {
        height: 394px;
        width: 100%;
        position: relative;
        background-color: #f0f0f0;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        justify-items: center;

        ul {
            margin: 42px 0 0;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        li {
            width: 138px;
            height: 256px;
            margin: 0 16px;
            position: relative;
            overflow: hidden;

            .surface-preview {
                position: absolute;
                left: 50%;
                top: 0;
                transform: translateX(-50%);
                width: 256px;
                height: 256px;
                padding: 0;

                &::v-deep > .loading {
                    background: none;
                }
            }
            img {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
            }

            & > span {
                display: none;
            }
        }

        & > p {
            margin-top: 26px;
            text-align: center;

            strong {
                display: block;
                height: 18px;
                font-size: 16px;
                color: #000000;
                line-height: 18px;
            }
            span {
                height: 16px;
                font-size: 14px;
                color: #555555;
                line-height: 16px;
            }
        }
    }

    .branding-preview-type {
        margin-left: 12px;

        & > p {
            height: 394px;
            width: 100%;
            position: relative;
            background-color: #f0f0f0;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            align-items: center;

            & > img {
                margin-top: 122px;
                width: 326px;
                height: 128px;
            }
            & > span {
                margin: 2px 48px;
                font-size: 16px;
                font-weight: bold;
                color: #555555;
                line-height: 20px;
                text-align: center;
            }
        }
    }
}

.branding-save {
    position: fixed;
    left: 228px;
    right: 0;
    padding-left: 32px;
    padding-right: 32px;
    bottom: 0;
    height: 90px;
    max-width: initial !important;
    width: initial !important;
    text-align: center;
    opacity: 0;
    z-index: 1;
    transition: opacity 0.5s;
    pointer-events: none;

    cite {
        border-top: 1px solid #dcdcdc;
        display: block;
        margin: 0 auto;
        max-width: 1080px;
        padding: 20px 0 40px;
        background: #fff;
    }
    button {
        width: 160px;
        height: 40px;
        margin: 0 12px;
        &[type='primary'] {
            width: 360px;
        }
    }

    &.active {
        opacity: 1;
        pointer-events: all;
    }
    &.loading::after {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(255, 255, 255, 0.9);
    }

    button {
        margin: 0 10px;
    }
}

.saving-dialog {
    &[status='loading']::v-deep .dialog-content {
        border-radius: 38px;
        & > h6 {
            display: none;
        }
    }
    &[status='success']::v-deep .dialog-content > h6 {
        display: none;
    }
    .saving-loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        width: 400px;
        height: 280px;
        background: #fafafa;
        border-radius: 38px;
        figure {
            width: 66px;
            height: 66px;
            margin-bottom: 24px;
            img {
                width: 100%;
                height: 100%;
            }
        }

        & > img {
            height: 8px;
        }
        strong {
            margin-top: 24px;
            font-size: 18px;
            color: #000000;
            line-height: 18px;
            text-align: center;
        }
    }

    .saving-success,
    .saving-failure {
        width: 320px;
        height: 414px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 40px 20px 26px;

        figure {
            margin-top: 50px;
            width: 80px;
            height: 80px;

            img {
                width: 100%;
                height: 100%;
            }
        }

        p {
            height: 120px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 16px;
            color: #000000;
            line-height: 20px;
            text-align: center;
            strong {
                color: #000000;
                margin-bottom: 8px;
            }
        }

        fieldset {
            display: flex;
            flex-direction: column;
            width: 100%;
            margin-top: 60px;
            button + button {
                margin-top: 8px;
            }
        }
    }
}
</style>
